/**
 * 记忆函数
 */

import { memoize } from 'lodash'
function getArea (r: number): number {
  console.log(r)
  return Math.PI  * r * r
}

const getAreaWithMemory1 = memoize(getArea)
console.log(getAreaWithMemory1(10)) // 只有第一次调用时执行getArea函数
console.log(getAreaWithMemory1(10))
console.log(getAreaWithMemory1(10))

// 模拟memoize

function myMemoize<T extends (...args: any) => any> (fn: T) {
  const cache = new Map()
  return function (...args) {
    let key = JSON.stringify(args)
    if (cache.has(key)) {
      return cache.get(key)
    }
    cache.set(key, fn(...args))
    return cache.get(key)
  }
}

const getAreaWithMemory2 = myMemoize(getArea)
console.log(getAreaWithMemory2(10)) // 只有第一次调用时执行getArea函数
console.log(getAreaWithMemory2(10))
console.log(getAreaWithMemory2(10))


export {}
